<script setup lang="ts">
import { ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getUserList, updateUserInfo } from "@/api/user";
import { maskPhone, maskEmail } from "@/utils/tools";
const imageUrl = import.meta.env.VITE_IMAGE_URL;
// 定义接口
interface UserData {
  id: string;
  phone: string;
  nickname: string | null;
  username: string | null;
  avatarUrl: string | null;
  gender: number;
  birthday: string | null;
  email: string | null;
  createdTime: string;
  token: string | null;
}

interface PageResponse {
  pageNo: number;
  pageSize: number;
  result: UserData[];
  total: number;
  totalPages: number;
  start: number;
  end: number;
}

// 搜索表单
const searchForm = reactive({
  keyword: "",
  status: "",
  userType: "",
  dateRange: [] as string[]
});

const loading = ref(false);
const tableData = ref<UserData[]>([]);
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
});

// 加载用户列表
const loadUserList = async () => {
  loading.value = true;
  try {
    const params = {
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      keyword: searchForm.keyword,
      status: searchForm.status || undefined,
      userType: searchForm.userType || undefined,
      startTime: searchForm.dateRange[0],
      endTime: searchForm.dateRange[1]
    };

    const response = await getUserList(params);
    if (response?.data) {
      tableData.value = response.data.result;
      pagination.total = response.data.total;
      pagination.current = response.data.pageNo;
    }
  } catch (error) {
    console.error("Failed to load users:", error);
    ElMessage.error("加载用户列表失败");
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleSearch = () => {
  pagination.current = 1;
  loadUserList();
};

// 处理重置
const handleReset = () => {
  searchForm.keyword = "";
  searchForm.status = "";
  searchForm.userType = "";
  searchForm.dateRange = [];
  handleSearch();
};

// 处理分页变化
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  pagination.current = 1;
  loadUserList();
};

const handleCurrentChange = (val: number) => {
  pagination.current = val;
  loadUserList();
};

// 处理删除用户
const handleDelete = (row: UserData) => {
  ElMessageBox.confirm(
    `确定要删除用户 ${row.nickname || row.username || row.phone} 吗？`,
    "警告",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }
  )
    .then(() => {
      // TODO: 调用删除用户API
      ElMessage.success("删除成功");
      loadUserList();
    })
    .catch(() => {});
};

// 格式化性别显示
const formatGender = (gender: number) => {
  const genderMap = {
    0: "女",
    1: "男",
    2: "未知"
  };
  return genderMap[gender as keyof typeof genderMap] || "未知";
};

// 获取用户显示名称
const getUserDisplayName = (user: UserData) => {
  return user.nickname || user.username || user.phone;
};

// 初始化加载
loadUserList();

const statusOptions = [
  { label: "全部状态", value: "" },
  { label: "正常", value: 1 },
  { label: "禁用", value: 0 }
];

const userTypeOptions = [
  { label: "全部类型", value: "" },
  { label: "普通用户", value: 1 }
];

// 添加用户详情对话框控制
const detailDialogVisible = ref(false);
const currentUser = ref({});

// 修改用户表单
const userForm = reactive({
  username: "",
  phone: "",
  email: "",
  userType: 1,
  status: 1
});

// 表单校验规则
const formRules = reactive({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" }
  ],
  phone: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号", trigger: "blur" }
  ],
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱地址", trigger: "blur" }
  ]
});

// 修改用户状态
const handleStatusChange = row => {
  const statusText = row.status === 1 ? "禁用" : "启用";
  ElMessageBox.confirm(`确定要${statusText}该用户吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      // TODO: 调用修改状态接口
      ElMessage.success(`${statusText}成功`);
    })
    .catch(() => {
      row.status = row.status === 1 ? 0 : 1; // 回滚状态
    });
};

// 添加作品和互动记录相关的接口
interface UserPost {
  id: number;
  title: string;
  content: string;
  images: string[];
  createTime: string;
  likeCount: number;
}

interface LikedPost {
  id: number;
  title: string;
  content: string;
  images: string[];
  createTime: string;
  likeCount: number;
  author: {
    username: string;
    avatar: string;
  };
}

// 添加标签页激活状态
const activeTab = ref("posts");

// 修改数据存储
const userPosts = ref<UserPost[]>([]);
const likedPosts = ref<LikedPost[]>([]);
const favoritePosts = ref<LikedPost[]>([]);

// 加载用户作品
const loadUserPosts = async (userId: number) => {
  loading.value = true;
  try {
    userPosts.value = [
      {
        id: 1,
        title: "汉服春游随拍",
        content: "今天和闺蜜一起去公园春游，穿着新买的汉服，拍了好多美照~",
        images: [
          "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
          "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
          "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg"
        ],
        createTime: "2024-01-20 14:30:00",
        likeCount: 128
      },
      {
        id: 2,
        title: "汉服写真 | 明制袄裙",
        content:
          "分享一组明制袄裙的写真，这套衣服真的很适合拍照，喜欢这种复古典雅的风格~",
        images: [
          "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
          "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
          "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
          "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg"
        ],
        createTime: "2024-01-19 10:15:00",
        likeCount: 256
      },
      {
        id: 3,
        title: "汉服日常 | 宋制对襟襦裙",
        content:
          "今天穿了宋制对襟襦裙去逛街，这套衣服真的很适合日常穿搭，舒适又好看~",
        images: [
          "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
          "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg"
        ],
        createTime: "2024-01-18 16:45:00",
        likeCount: 89
      }
    ];
  } catch (error) {
    ElMessage.error("加载用户作品失败");
  } finally {
    loading.value = false;
  }
};

// 加载用户点赞的客片
const loadLikedPosts = async (userId: number) => {
  loading.value = true;
  try {
    likedPosts.value = [
      {
        id: 1,
        title: "汉服春游随拍",
        content: "今天和闺蜜一起去公园春游，穿着新买的汉服，拍了好多美照~",
        images: [
          "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
          "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
          "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg"
        ],
        createTime: "2024-01-20 14:30:00",
        likeCount: 128,
        author: {
          username: "花想容",
          avatar: "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg"
        }
      },
      {
        id: 2,
        title: "魏晋风汉服写真",
        content:
          "魏晋风格的汉服真的很有特色，这次约拍选择了古建筑作为背景，搭配飘逸的纱衣~",
        images: [
          "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
          "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
          "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg"
        ],
        createTime: "2024-01-19 15:30:00",
        likeCount: 167,
        author: {
          username: "梨花白",
          avatar: "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg"
        }
      },
      {
        id: 3,
        title: "简约风格汉服日常",
        content:
          "分享一套简约风格的汉服日常，这种款式很适合平时穿着，不会太过繁复~",
        images: [
          "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
          "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
          "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
          "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg"
        ],
        createTime: "2024-01-18 11:25:00",
        likeCount: 198,
        author: {
          username: "初白",
          avatar: "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg"
        }
      }
    ];
  } catch (error) {
    ElMessage.error("加载点赞记录失败");
  } finally {
    loading.value = false;
  }
};

// 加载用户收藏的客片
const loadFavoritePosts = async (userId: number) => {
  loading.value = true;
  try {
    favoritePosts.value = [
      {
        id: 1,
        title: "汉服写真 | 明制袄裙",
        content:
          "分享一组明制袄裙的写真，这套衣服真的很适合拍照，喜欢这种复古典雅的风格~",
        images: [
          "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
          "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
          "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
          "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg"
        ],
        createTime: "2024-01-19 10:15:00",
        likeCount: 256,
        author: {
          username: "清辞",
          avatar: "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg"
        }
      },
      {
        id: 2,
        title: "汉服摄影 | 唐制齐胸襦裙",
        content:
          "这次拍摄选择了唐制齐胸襦裙，搭配了传统发饰和配件，尝试还原古代美人的风韵~",
        images: [
          "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
          "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
          "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
          "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
          "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg"
        ],
        createTime: "2024-01-17 09:20:00",
        likeCount: 345,
        author: {
          username: "青衣",
          avatar: "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg"
        }
      },
      {
        id: 3,
        title: "汉服日常 | 宋制对襟襦裙",
        content:
          "今天穿了宋制对襟襦裙去逛街，这套衣服真的很适合日常穿搭，舒适又好看~",
        images: [
          "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg",
          "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg"
        ],
        createTime: "2024-01-18 16:45:00",
        likeCount: 89,
        author: {
          username: "墨兮",
          avatar: "https://pic1.imgdb.cn/item/6787428fd0e0a243d4f465c6.jpg"
        }
      }
    ];
  } catch (error) {
    ElMessage.error("加载收藏记录失败");
  } finally {
    loading.value = false;
  }
};

// 修改查看详情方法
const handleViewDetail = (row: any) => {
  currentUser.value = row;
  detailDialogVisible.value = true;
  // 加载用户数据
  loadUserPosts(row.id);
  loadLikedPosts(row.id);
  loadFavoritePosts(row.id);
};

// 预览图片
const previewVisible = ref(false);
const previewImages = ref<string[]>([]);
const previewIndex = ref(0);

const handlePreviewImage = (images: string[], index: number) => {
  previewImages.value = images;
  previewIndex.value = index;
  previewVisible.value = true;
};

// 添加编辑对话框控制
const editDialogVisible = ref(false);

// 修改编辑用户方法
const handleEdit = (row: any) => {
  Object.assign(userForm, row);
  editDialogVisible.value = true;
};

// 提交用户信息
const formRef = ref();
const submitForm = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(valid => {
    if (valid) {
      // TODO: 调用更新用户信息接口
      ElMessage.success("更新成功");
      editDialogVisible.value = false;
    }
  });
};

defineOptions({
  name: "Users"
});
</script>

<template>
  <div class="users-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="用户名/手机号/邮箱"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="注册时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span class="title">用户列表</span>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column label="用户信息" min-width="200">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :size="40" :src="imageUrl + row.avatarUrl" />
              <div class="user-detail">
                <div class="username">{{ getUserDisplayName(row) }}</div>
                <div class="contact">
                  <div>{{ maskPhone(row.phone) }}</div>
                  <div v-if="row.email">{{ maskEmail(row.email) }}</div>
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="性别" width="80" align="center">
          <template #default="{ row }">
            {{ formatGender(row.gender) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="birthday"
          label="生日"
          width="120"
          align="center"
        />
        <el-table-column
          prop="createdTime"
          label="注册时间"
          width="160"
          align="center"
        />
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="{ row }">
            <!-- <el-button link type="primary" @click="handleViewDetail(row)">
              查看
            </el-button> -->
            <el-button link type="primary" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button link type="danger" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          background
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 用户详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      :title="`${currentUser.username || '用户'}的动态`"
      width="800px"
      class="user-detail-dialog"
      :modal-append-to-body="false"
    >
      <el-tabs v-model="activeTab" class="detail-tabs">
        <!-- 发布作品标签页 -->
        <el-tab-pane label="发布的作品" name="posts">
          <div class="scroll-container">
            <div class="post-list">
              <el-empty v-if="!userPosts.length" description="暂无发布作品" />
              <el-card
                v-for="post in userPosts"
                :key="post.id"
                class="post-card"
                shadow="hover"
              >
                <div class="post-header">
                  <h4 class="title">{{ post.title }}</h4>
                  <span class="time">{{ post.createTime }}</span>
                </div>
                <p class="content">{{ post.content }}</p>
                <div class="images">
                  <el-image
                    v-for="(image, index) in post.images"
                    :key="index"
                    :src="image"
                    fit="cover"
                    class="image"
                    @click="handlePreviewImage(post.images, index)"
                  />
                </div>
                <div class="stats">
                  <span class="like-count">
                    <el-icon><Star /></el-icon>
                    {{ post.likeCount }}
                  </span>
                </div>
              </el-card>
            </div>
          </div>
        </el-tab-pane>

        <!-- 点赞的客片标签页 -->
        <el-tab-pane label="点赞的客片" name="likes">
          <div class="scroll-container">
            <div class="post-list">
              <el-empty v-if="!likedPosts.length" description="暂无点赞记录" />
              <el-card
                v-for="post in likedPosts"
                :key="post.id"
                class="post-card"
                shadow="hover"
              >
                <div class="post-header">
                  <div class="author-info">
                    <el-avatar :src="post.author.avatar" :size="32" />
                    <span class="username">{{ post.author.username }}</span>
                  </div>
                  <span class="time">{{ post.createTime }}</span>
                </div>
                <h4 class="title">{{ post.title }}</h4>
                <p class="content">{{ post.content }}</p>
                <div class="images">
                  <el-image
                    v-for="(image, index) in post.images"
                    :key="index"
                    :src="image"
                    fit="cover"
                    class="image"
                    @click="handlePreviewImage(post.images, index)"
                  />
                </div>
              </el-card>
            </div>
          </div>
        </el-tab-pane>

        <!-- 收藏的客片标签页 -->
        <el-tab-pane label="收藏的客片" name="favorites">
          <div class="scroll-container">
            <div class="post-list">
              <el-empty
                v-if="!favoritePosts.length"
                description="暂无收藏记录"
              />
              <el-card
                v-for="post in favoritePosts"
                :key="post.id"
                class="post-card"
                shadow="hover"
              >
                <div class="post-header">
                  <div class="author-info">
                    <el-avatar :src="post.author.avatar" :size="32" />
                    <span class="username">{{ post.author.username }}</span>
                  </div>
                  <span class="time">{{ post.createTime }}</span>
                </div>
                <h4 class="title">{{ post.title }}</h4>
                <p class="content">{{ post.content }}</p>
                <div class="images">
                  <el-image
                    v-for="(image, index) in post.images"
                    :key="index"
                    :src="image"
                    fit="cover"
                    class="image"
                    @click="handlePreviewImage(post.images, index)"
                  />
                </div>
              </el-card>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <!-- 图片预览 -->
    <el-image-viewer
      v-if="previewVisible"
      :url-list="previewImages"
      :initial-index="previewIndex"
      @close="previewVisible = false"
    />

    <!-- 添加编辑用户对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑用户信息" width="500px">
      <el-form
        ref="formRef"
        :model="userForm"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" />
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>

        <el-form-item label="用户类型" prop="userType">
          <el-select v-model="userForm.userType">
            <el-option
              v-for="item in userTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select v-model="userForm.status">
            <el-option
              v-for="item in statusOptions.filter(item => item.value !== '')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.users-container {
  padding: 20px;
  background: #f5f7fa;

  .search-card {
    margin-bottom: 20px;
  }

  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .title {
        font-size: 16px;
        font-weight: bold;
        color: #303133;
      }
    }

    .user-info {
      display: flex;
      align-items: center;
      gap: 12px;

      .user-detail {
        .username {
          font-size: 14px;
          font-weight: 500;
          color: #303133;
          margin-bottom: 4px;
        }

        .contact {
          font-size: 12px;
          color: #909399;

          div {
            line-height: 1.4;
          }
        }
      }
    }
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  :deep(.el-tag) {
    min-width: 80px;
  }

  .user-detail-dialog {
    :deep(.el-dialog) {
      display: flex;
      flex-direction: column;
      max-height: 90vh;
      margin-top: 5vh !important;
    }

    :deep(.el-dialog__header) {
      padding: 20px;
      margin: 0;
      border-bottom: 1px solid var(--el-border-color-light);
    }

    :deep(.el-dialog__body) {
      padding: 0;
      margin: 0;
      height: calc(90vh - 120px); // 减去header和footer的高度
      overflow: hidden; // 防止出现双滚动条
    }

    .detail-tabs {
      height: 100%;
      display: flex;
      flex-direction: column;

      :deep(.el-tabs__header) {
        margin: 0;
        padding: 0 20px;
        background: var(--el-bg-color);
        border-bottom: 1px solid var(--el-border-color-light);
      }

      :deep(.el-tabs__content) {
        flex: 1;
        overflow-y: auto;
        padding: 20px;

        // 美化滚动条
        &::-webkit-scrollbar {
          width: 6px;
        }

        &::-webkit-scrollbar-thumb {
          background: var(--el-border-color-darker);
          border-radius: 3px;
        }

        &::-webkit-scrollbar-track {
          background: var(--el-fill-color-light);
          border-radius: 3px;
        }
      }
    }

    .post-list {
      display: flex;
      flex-direction: column;
      gap: 16px;

      .post-card {
        margin: 0; // 移除卡片默认外边距

        .post-header {
          padding: 16px;
          border-bottom: 1px solid var(--el-border-color-lighter);
          background: var(--el-fill-color-light);

          .author-info {
            .username {
              color: var(--el-color-primary);
            }
          }

          .time {
            font-size: 12px;
          }
        }

        .title {
          margin: 16px;
          font-size: 16px;
          font-weight: 500;
        }

        .content {
          margin: 0 16px 16px;
          font-size: 14px;
          line-height: 1.6;
          color: var(--el-text-color-regular);
        }

        .images {
          margin: 0 16px 16px;
          display: grid;
          grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
          gap: 8px;

          .image {
            width: 100%;
            height: 120px;
            border-radius: 4px;
            transition: all 0.3s ease;

            &:hover {
              transform: scale(1.05);
              box-shadow: var(--el-box-shadow-light);
            }
          }
        }

        .stats {
          padding: 12px 16px;
          border-top: 1px solid var(--el-border-color-lighter);
          background: var(--el-fill-color-light);

          .like-count {
            color: var(--el-color-danger);
            font-weight: 500;
          }
        }
      }
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }
}
</style>
